package com.tyl.demo01;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicketDemo02 {
    public static void main(String[] args) {
        //并发：多个线程同时操作一个资源。把资源丢入线程中即可
        Ticket2 ticket=new Ticket2();
        new Thread(()->{for (int i = 0; i < 60; i++)ticket.sale();},"B").start();
        new Thread(()->{for (int i = 0; i < 60; i++)ticket.sale();},"A").start();
        new Thread(()->{for (int i = 0; i < 60; i++)ticket.sale();},"C").start();
    }
}

class Ticket2{
    private int number=50;
    Lock lock=new ReentrantLock();
    //卖票
    public  void sale(){
        lock.lock();//加锁
        try {
            //代码块
            if(number>0){
                Thread.sleep(200);
                System.out.println(Thread.currentThread().getName()+"卖出了"+(51-(number--))+"张票"+"剩余"+number+"张票");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();//解锁
        }
    }
}
